package com.zy.edu.config.api;

import com.zy.edu.bean.ResponseInfo;
import com.zy.edu.config.redis.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

@Service
public class ApiTokenService {

    private static final String TOKEN_NAME = "apiToken";
    private static final Integer EXPIRE_TIME_MINUTE = 60;// 过期时间, 60s, 一分钟
    private static final Integer EXPIRE_TIME_HOUR = 60 * 60;// 过期时间, 一小时
    private static final Integer EXPIRE_TIME_DAY = 60 * 60 * 24;// 过期时间, 一天
    private static final String TOKEN_PREFIX = "apiToken:";
    @Autowired
    private RedisUtil redisUtil;

    public Map createToken() {
        String str = UUID.randomUUID().toString().replaceAll("-", "");
        StrBuilder token = new StrBuilder();
        token.append(TOKEN_PREFIX).append(str);

        redisUtil.set(token.toString(), token.toString(), EXPIRE_TIME_MINUTE);

        return ResponseInfo.success(token.toString());
    }

    public void checkToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader(TOKEN_NAME);
        if (StringUtils.isBlank(token)) {// header中不存在token
            token = request.getParameter(TOKEN_NAME);
            if (StringUtils.isBlank(token)) {// parameter中也不存在token
                throw new Exception("参数不存在");
            }
        }

        if (!redisUtil.hasKey(token)) {
            throw new Exception("请勿重复操作");
        }

        boolean del = redisUtil.del(token);
        if (!del) {
            throw new Exception("请勿重复操作");
        }
    }

}

